package jp.syuriken.snsw.terenaibot.internal;

import java.util.logging.Level;

import jp.syuriken.snsw.terenaibot.BotConfiguration;
import jp.syuriken.snsw.terenaibot.WorkJob;

/**
 * JobQueueからジョブを取得して消費するクラス
 * 
 * @author $Author: snswinhaiku.lo@gmail.com $ */
public class JobWorkerThread extends Thread {
	
	private final BotConfiguration botConfiguration;
	
	private ThreadHolder workerThreadHolder;
	
	private boolean isFinish = false;
	

	/**
	 * インスタンスを生成する。
	 * @param threadGroup スレッドグループ 
	 * @param botConfiguration 設定
	 */
	public JobWorkerThread(ThreadGroup threadGroup, BotConfiguration botConfiguration) {
		super(threadGroup, "tbotsys-jobworker");
		this.botConfiguration = botConfiguration;
		workerThreadHolder = new ThreadHolder();
	}
	
	/**
	 * このスレッドのスレッドホルダを取得する
	 * 
	 * @return スレッドホルダ
	 */
	public ThreadHolder getWorkerThreadHolder() {
		return workerThreadHolder;
	}
	
	/**
	 * スレッドを停止する準備をする。
	 */
	public void quit() {
		isFinish = true;
		botConfiguration.getJobQueue().setJobWorkerThread(null, null);
	}
	
	@Override
	public void run() {
		while (!isFinish) {
			try {
				while (botConfiguration.getJobQueue().isEmpty() == false) {
					WorkJob job = botConfiguration.getJobQueue().getJob();
					if (job != null) {
						job.work();
					}
				}
			} catch (RuntimeException e) {
				botConfiguration.getLogger().log(Level.SEVERE, e, "Not caught exception (thread tbotsys-jobworker)");
			}
			try {
				synchronized (workerThreadHolder) {
					if (!isFinish) {
						workerThreadHolder.wait();
					}
				}
			} catch (InterruptedException e) {
				// do nothing
			}
		}
		WorkJob job;
		while ((job = botConfiguration.getJobQueue().getJob()) != null) {
			try {
				job.work();
			} catch (RuntimeException e) {
				botConfiguration.getLogger().log(Level.SEVERE, e, "Not caught exception (thread tbotsys-jobworker)");
			}
		}
	}
}
